﻿using System;
using System.Windows;

namespace Kinect
{
    public class GPoint
    {
        public double x, y;

        public GPoint(Point pt)
        {
            this.x = pt.X;
            this.y = pt.Y;
        }
        public GPoint()
        {
        }
        public GPoint(double x, double y)
        {
            this.x = x;
            this.y = y;
        }
        public GPoint(Microsoft.Research.Kinect.Nui.Vector pt)
        {
            this.x = pt.X;
            this.y = pt.Y;
        }
        public GPoint(System.Drawing.Point pt)
        {
            this.x = pt.X;
            this.y = pt.Y;
        }
        public GPoint add(GPoint rhs) 
        {
            return new GPoint(x + rhs.x, y + rhs.y);
        }
        public GPoint sub(GPoint rhs)
        {
            return new GPoint(x - rhs.x, y - rhs.y);
        }
        public GPoint mul(double rhs)
        {
            return new GPoint(x * rhs, y * rhs);
        }
        public static GPoint add(GPoint a, GPoint b)
        {
            return a.add(b);
        }
        public static double Cross(GPoint A, GPoint B)
        {
            return A.x * B.y - B.x * A.y;
        }
        public static double triArea(GPoint P0, GPoint P1, GPoint P2)
        {
            return GPoint.Cross(P1.sub(P0), P2.sub(P0));
        }
        public static double areaPoly(GPoint[] poly)
        {
            double totArea = 0;
            int n = poly.Length;
            if (n <= 2) return 0;

            GPoint P0 = poly[0];
            for (int i = 0; i < n; i++)
            {
                GPoint P1 = poly[i];
                GPoint P2 = poly[(i + 1) % n];
                totArea += triArea(P0, P1, P2);
            }
            return Math.Abs(totArea);
        }
        public bool inPoly(GPoint[] poly)
        {
            int n = poly.Length;
            double totArea = 0;
            double polyArea = areaPoly(poly);
            GPoint P0 = this;
            for (int i = 0; i < n; i++)
            {
                GPoint P1 = poly[i];
                GPoint P2 = poly[(i + 1) % n];
                totArea += Math.Abs(triArea(P0, P1, P2));
            }
            totArea = Math.Abs(totArea);
            if (!GMath.deq(totArea, polyArea))
            {
                int a = 10;
                ++a;
            }
            return GMath.deq(totArea, polyArea);
        }
    }
}
